﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Threading;
using Kn.DLMS;

namespace UpgadeFileCombineApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private byte[] Image1;
        private byte[] ImageMcu2;
        private byte[] Image2;

        private byte[] ImageSelectMcu;

        private string s_ImageName1 = "";
        private string s_Image2Name1 = "";
        private string s_ImageName2 = "";
        private string s_str5007Ver = "";
        private string s_strSocaddrVer = "";
        private string strfileCode = null;

        private string strMcuHardwareVer = "";

        string txt_upgade1_path = "";
        string txt_upgade2_path = "";

        private byte[] BootImage; //boot程序

        private void btn_open1_Click(object sender, EventArgs e)
        {
            try
            {
                this.txt_upgade1.Text = "";
                this.Image1 = null;
                label_MCUSofewareVersion.Text = "";
                label_MCUHardwareVersion.Text = "";
                label_McuImageSize.Text = "";
                label_McuProjectNo.Text = "";
                labelSave.Text = "";
                label_Result.Text = "";
                label_MCU项目编号.Visible = false;
                label_MCU硬件版本号.Visible = false;
                label_MCU软件版本号.Visible = false;
                label_MCU程序大小.Visible = false;

                OpenFileDialog dlg = new OpenFileDialog();
                string sPath = AppConfigProcess.GetConfigXml("MCUPATH"); 
                string sFilterIndex = AppConfigProcess.GetConfigXml("FILEFORMAT");
                int FilterIndex = 1;
                if(sFilterIndex != "")
                {
                    FilterIndex = Convert.ToInt32(sFilterIndex);
                }
                if (Directory.Exists(sPath)) dlg.InitialDirectory = sPath;

                dlg.Filter = "Image Files (*.bin)|*.bin|Image Files (*.mot)|*.mot|Image Files (*.hex)|*.hex|All files (*.*)|*.*";
                //dlg.DefaultExt = ".bin";
                //dlg.DefaultExt = ".mot";
                dlg.FilterIndex = FilterIndex;
                dlg.ValidateNames = true;
                dlg.Multiselect = false;
                
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    sFilterIndex = dlg.FilterIndex.ToString();
                    AppConfigProcess.SetConfigValue("FILEFORMAT", sFilterIndex);     //保持最近一次选择的文件格式
                    this.btn_Combine.Enabled = true;
                    this.txt_upgade1.Text = dlg.FileName;
                    txt_upgade1_path = dlg.FileName;
                    this.txt_upgade1.Text = Path.GetFileName(txt_upgade1_path);


                    if (this.s_ImageName1 == "")
                    {
                        if (string.Compare(Path.GetExtension(txt_upgade1_path), ".xml", true) == 0)
                        {
                            XmlDocument doc = new XmlDocument();
                            doc.Load(txt_upgade1_path);
                            byte[] arr = GetIdentification(doc.ChildNodes);
                            if (Kn.DLMS.GXByteBuffer.IsAsciiString(arr))
                            {
                                this.s_ImageName1 = ASCIIEncoding.ASCII.GetString(arr);
                            }
                            else
                            {
                                this.s_ImageName1 = Kn.DLMS.GXDLMSTranslator.ToHex(arr);
                            }
                        }
                        else
                        {
                            this.s_ImageName1 = Path.GetFileNameWithoutExtension(dlg.FileName);
                        }
                    }

                    if (string.Compare(Path.GetExtension(txt_upgade1_path), ".xml", true) == 0)
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.Load(txt_upgade1_path);
                        byte[] image = null;
                        GetImage(doc.ChildNodes, ref image);
                        this.Image1 = image;
                    }
                    else
                    {
                        FileInfo info = new FileInfo(txt_upgade1_path);
                        if (info.Extension == ".hex" || info.Extension == ".HEX" || info.Extension == ".Hex")
                        {
                            HexFile tmp = new HexFile(txt_upgade1_path);
                            this.Image1 = tmp.AppImage;
                        }
                        if (info.Extension == ".mot" || info.Extension == ".MOT" || info.Extension == ".Mot")
                        {
                            int BootSize = 0x2000;
                            string strBootSize = AppConfigProcess.GetConfigXml("McuAppBootSize");     //保持最近一次选择的文件格式
                            if (strBootSize == "")
                            {
                                AppConfigProcess.SetConfigValue("McuAppBootSize", BootSize.ToString());
                            }
                            else
                            {
                                BootSize = Convert.ToInt32(strBootSize);
                            }
                            SRecordView tmp = new SRecordView(txt_upgade1_path, false, BootSize);  //!!
                            this.Image1 = tmp.AppImage;
                        }
                        if(info.Extension == ".bin" || info.Extension == ".BIN" || info.Extension == ".Bin")
                        {
                            this.Image1 = File.ReadAllBytes(txt_upgade1_path);
                        }
                        
                    }

                    string strL = "";

                    // 5007 /  5011
                    if (this.Image1.Length > 8179)
                    {
                        this.strfileCode = ASCIIEncoding.ASCII.GetString(this.Image1, 8160, 5);        //根据实际定义  0x1FE0  const unsigned char c_KnSoft[11]__attribute__( (at(0x3FE0)))="5011H210727";      // 内部程序版本号 //
                        this.s_str5007Ver = ASCIIEncoding.ASCII.GetString(this.Image1, 8171, 9);       //根据实际定义  0x1FEB  const unsigned char c_SoftVersion[10]__attribute__( (at(0x3FEB)))="040521.06.";  // 软件版本号10字节//
                        strL = ASCIIEncoding.ASCII.GetString(this.Image1, this.Image1.Length - 25, 3);
                        this.strMcuHardwareVer = ASCIIEncoding.ASCII.GetString(this.Image1, 0x1FF5, 8);//硬件版本号
                    }

                    // 5012 Bin文件
                    if (this.Image1.Length > 5012 &&　this.strfileCode.Substring(0, 2) != "50")
                    {
                        this.strfileCode = ASCIIEncoding.ASCII.GetString(this.Image1, 4992, 5);      //0x1380  #pragma section @@CNST VERCST  AT  3380H const unsigned char c_KnSoft[11]="5012.210817";           // 软件版本号 //
                        this.s_str5007Ver = ASCIIEncoding.ASCII.GetString(this.Image1, 5003, 9);     //0x138B  #pragma section @@CNST VERCST  AT  3380Hconst unsigned char c_SoftVersion[12]="170821.01.04";     // 内部程序版本号 //
                        strL = ASCIIEncoding.ASCII.GetString(this.Image1, this.Image1.Length - 25, 3);
                        this.strMcuHardwareVer = ASCIIEncoding.ASCII.GetString(this.Image1, 0x1397, 8);   //0x1397  #pragma section @@CNST VERCST  AT  3380H c_HardVersion[9]="5012V0.6";         // 硬件版本号 //
                    }

                    label_MCU项目编号.Visible = true;
                    label_MCU硬件版本号.Visible = true;
                    label_MCU软件版本号.Visible = true;
                    label_MCU程序大小.Visible = true;

                    label_MCUSofewareVersion.Text = s_str5007Ver;
                    label_MCUHardwareVersion.Text = strMcuHardwareVer;
                    float flen = this.Image1.Length;
                    flen /= 1024;
                    label_McuImageSize.Text = /*this.Image1.Length.ToString() + "B/" +*/ flen.ToString("000.00")+"KB";
                    label_McuProjectNo.Text = this.strfileCode.Replace(".", "");

                    if ((this.strfileCode.Substring(0, 2) != "50" /*|| this.strfileCode.Substring(4, 1) != ".")*/ || strL == "L00"))
                    {
                        this.Image1 = null;
                        this.txt_upgade1.Text = "";
                        throw new Exception("illegal file ,please re-select!");
                    }
           
                    if (this.strfileCode == "5007.")
                    {
                        if (this.Image1.Length > (119 * 1024))
                        {
                            MessageBox.Show("Mcu file length > 119 KB","");
                        }
                    }

                    else if (this.strfileCode == "5011.")
                    {
                        if (this.Image1.Length > (200 * 1024))
                        {
                            MessageBox.Show("Mcu file length > 200 KB");
                        }
                    }

                    else if(this.strfileCode == "5012.")
                    {
                        if (this.Image1.Length > (87 * 1024))
                        {
                            MessageBox.Show("Mcu file length > 87 KB");
                        }
                    }

                    //加载APP成功,开始加载boot
                    string bootfile_path = AppDomain.CurrentDomain.BaseDirectory + @"KND5011BOOT V002.mot";
                    SRecordView tmp1 = new SRecordView(bootfile_path, false, 0);  //!!解析boot.mot 程序文件
                    this.BootImage = tmp1.AppImage;
                    string BootVer = ASCIIEncoding.ASCII.GetString(this.BootImage, 8064, 4);

                    float flen1 = this.BootImage.Length;
                    flen /= 1024;
                    string BootImageSize = this.BootImage.Length.ToString() + "B/" + flen1.ToString("000.00") + "KB";

                    AppConfigProcess.SetConfigValue("MCUPATH", Path.GetDirectoryName(dlg.FileName));     //保持最近一次选择的文件格式
                }
            }
            catch (Exception ex)
            {
                this.Image1 = null;
                label_MCUSofewareVersion.Text = "";
                label_MCUHardwareVersion.Text = "";
                label_McuImageSize.Text = "";
                label_McuProjectNo.Text = "";

                label_MCU项目编号.Visible = false;
                label_MCU硬件版本号.Visible = false;
                label_MCU软件版本号.Visible = false;
                label_MCU程序大小.Visible = false;
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Try to get identification from xml file.
        /// </summary>
        /// <param name="nodes">XML nodes.</param>
        /// <returns>Found dentification.</returns>
        public static byte[] GetIdentification(XmlNodeList nodes)
        {
            foreach (XmlNode it in nodes)
            {
                if (it.NodeType == XmlNodeType.Element && it.ChildNodes.Count == 1 && it.ChildNodes[0].NodeType == XmlNodeType.Text &&
                    it.Name.Contains("Identification"))
                {
                    return GXDLMSTranslator.HexToBytes(it.InnerText);
                }
                else
                {
                    if (it.ChildNodes.Count != 0 && it.FirstChild.NodeType != XmlNodeType.Text)
                    {
                        byte[] ret = GetIdentification(it.ChildNodes);
                        if (ret != null)
                        {
                            return ret;
                        }
                    }
                }
            }

            return null;
        }

        /// <summary>
        /// Try to get identification from xml file.
        /// </summary>
        /// <param name="nodes">XML nodes.</param>
        /// <returns>Found dentification.</returns>
        public static void GetImage(XmlNodeList nodes, ref byte[] image)
        {
            foreach (XmlNode it in nodes)
            {
                if (it.NodeType == XmlNodeType.Element && it.ChildNodes.Count == 1 && it.ChildNodes[0].NodeType == XmlNodeType.Text)
                {
                    byte[] tmp = GXDLMSTranslator.HexToBytes(it.InnerText);
                    if (image == null || tmp.Length > image.Length)
                    {
                        image = tmp;
                    }
                }
                else
                {
                    if (it.ChildNodes.Count != 0 && it.FirstChild.NodeType != XmlNodeType.Text)
                    {
                        GetImage(it.ChildNodes, ref image);
                    }
                }
            }
        }

        private void btn_open2_Click(object sender, EventArgs e)
        {
            string strfileSOCADDR = null;

            try
            {
                this.txt_upgade2.Text = "";
                label_SOC软件版本号.Text = "";
                OpenFileDialog dlg = new OpenFileDialog();
                string sPath = AppConfigProcess.GetConfigXml("SOCPATH");
                if (Directory.Exists(sPath)) dlg.InitialDirectory = sPath;
                labelSave.Text = "";
                label_Result.Text = "";
                dlg.Filter = "Image Files (*.bin)|*.bin|All files (*.*)|*.*";
                dlg.DefaultExt = ".bin";
                dlg.ValidateNames = true;
                dlg.Multiselect = false;

                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    this.btn_Combine.Enabled = true;
                    txt_upgade2_path = dlg.FileName;
                    this.txt_upgade2.Text = Path.GetFileName(txt_upgade2_path);

                    if (this.s_ImageName2 == "")
                    {
                        if (string.Compare(Path.GetExtension(txt_upgade2_path), ".xml", true) == 0)
                        {
                            XmlDocument doc = new XmlDocument();
                            doc.Load(txt_upgade2_path);
                            byte[] arr = GetIdentification(doc.ChildNodes);
                            if (Kn.DLMS.GXByteBuffer.IsAsciiString(arr))
                            {
                                this.s_ImageName2 = ASCIIEncoding.ASCII.GetString(arr);
                            }
                            else
                            {
                                this.s_ImageName2 = Kn.DLMS.GXDLMSTranslator.ToHex(arr);
                            }
                        }
                        else
                        {
                            this.s_ImageName2 = Path.GetFileNameWithoutExtension(dlg.FileName);
                        }
                    }

                    if (string.Compare(Path.GetExtension(txt_upgade2_path), ".xml", true) == 0)
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.Load(txt_upgade2_path);
                        byte[] image = null;
                        GetImage(doc.ChildNodes, ref image);
                        this.Image2 = image;
                    }
                    else
                    {
                        this.Image2 = File.ReadAllBytes(txt_upgade2_path);
                    }

                    string strL = "";
                    if (this.Image2.Length > (3056 + 7))
                    {
                        strfileSOCADDR = ASCIIEncoding.ASCII.GetString(this.Image2, 3056, 7);
                        this.s_strSocaddrVer = ASCIIEncoding.ASCII.GetString(this.Image2, 3063, 8);
                        label_SOC软件版本号.Text = "计量SOC软件版本: " + this.s_strSocaddrVer;
                        label_SOC软件版本号.Visible = true;
                       strL = ASCIIEncoding.ASCII.GetString(this.Image2, this.Image2.Length - 25, 1);
                    }

                    if (strfileSOCADDR != "SOCADDR" ||  strL == "L")
                    {
                        this.Image2 = null;
                        this.txt_upgade2.Text = "";
                        throw new Exception("illegal file ,please re-select!");
                    }

                    if (this.Image2.Length > (31 * 1024))
                    {
                        this.btn_Combine.Enabled = this.txt_upgade1.Text == "" ? false : true;
                        this.txt_upgade2.Text = "";
                        throw new Exception("Soc file length > 31 KB");
                    }

                    AppConfigProcess.SetConfigValue("SOCPATH", Path.GetDirectoryName(dlg.FileName));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FileStream pFileStream = null;
            string fileName = null;
            byte[] ByteInfoArr = null;
            this.labelSave.Text = "";
            label_Result.Text = "";
            string strSaveFileName = "";
            string strSaveFileName1 = "";
            string strSaveFileName2 = "";

            try
            {
                if (this.txt_upgade1.Text == "" && this.txt_upgade2.Text == "" )
                {
                    throw new Exception("Please select one file at least!");
                }

                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Title = "Combine Upgade file";
                saveFileDialog.Filter = "BIN format file(*.BIN)|*.BIN";
                saveFileDialog.RestoreDirectory = false;
                saveFileDialog.CheckPathExists = true;
          
                string sPath = AppConfigProcess.GetConfigXml("SAVEPATH");
                if (Directory.Exists(sPath)) saveFileDialog.InitialDirectory = sPath;


                //确定文件名
                if (this.txt_upgade1.Text != "" && this.txt_upgade2.Text != "")
                {
                    strSaveFileName1 = "MS" + label_McuProjectNo.Text + label_MCUSofewareVersion.Text.Replace(".", "");
                }

                else if (this.txt_upgade1.Text != "" && this.txt_upgade2.Text  == "")
                {
                    strSaveFileName1 = "M" + label_McuProjectNo.Text + label_MCUSofewareVersion.Text.Replace(".", "");
                }

                else if (this.txt_upgade1.Text == "" && this.txt_upgade2.Text != "")
                {
                    strSaveFileName1 = "S"  + this.s_strSocaddrVer.Substring(1, 7);
                }

                /*

                //确定文件名
                if (this.txt_Mcu2upgade1.Text != "" && this.txt_upgade2.Text != "")
                {
                    strSaveFileName2 = "MS" + label_Mcu2ProjectNo.Text + label_MCU2SofewareVersion.Text.Replace(".", "");
                }

                else if (this.txt_Mcu2upgade1.Text != "" && this.txt_upgade2.Text == "")
                {
                    strSaveFileName2 = "M" + label_Mcu2ProjectNo.Text + label_MCU2SofewareVersion.Text.Replace(".", "");
                }

                else if (this.txt_Mcu2upgade1.Text == "" && this.txt_upgade2.Text != "")
                {
                    strSaveFileName2 = "S" + this.s_strSocaddrVer.Substring(1, 7);
                }
                */
                saveFileDialog.FileName = strSaveFileName1 + strSaveFileName2;
                

                DialogResult dialogResult = saveFileDialog.ShowDialog(this);
                Int32 iIamgelen1 = (this.txt_upgade1.Text != "" && this.Image1 != null) ? this.Image1.Length : 0;
                Int32 iIamgelen2 = (this.txt_upgade2.Text != "" && this.Image2 != null) ? this.Image2.Length : 0;

                //Int32 iImageMcu2Len = (this.txt_Mcu2upgade1.Text != "" && this.ImageMcu2 != null) ? this.ImageMcu2.Length : 0;

                if (dialogResult == DialogResult.OK)
                {

                    fileName = saveFileDialog.FileName;
                    System.IO.File.Delete(fileName);
                    pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);

                    if(strSaveFileName1 != "")
                    {
                        //升级文件1
                        byte[] resArr = new byte[iIamgelen1 + iIamgelen2];
                        if (this.txt_upgade1.Text != "" && this.Image1 != null)
                        {
                            this.Image1.CopyTo(resArr, 0);
                            if (this.txt_upgade2.Text != "" && this.Image2 != null)
                            {
                                this.Image2.CopyTo(resArr, iIamgelen1);
                            }
                        }
                        else if (this.txt_upgade2.Text != "" && this.Image2 != null)
                        {
                            this.Image2.CopyTo(resArr, 0);
                        }
                        //fileName = saveFileDialog.FileName;
                        //System.IO.File.Delete(fileName);
                        //pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);
                        pFileStream.Write(resArr, 0, resArr.Length);

                        CRC32.Reset();
                        CRC32.Crc(resArr, resArr.Length);
                        string strCrc = CRC32.crc.ToString("X8");
                        string strAddInfo = "L" + iIamgelen1.ToString("X8") + iIamgelen2.ToString("X8") + strCrc;    //          
                        ByteInfoArr = ASCIIEncoding.ASCII.GetBytes(strAddInfo);
                        pFileStream.Write(ByteInfoArr, 0, ByteInfoArr.Length);  //再次写入文件     
                    }
                    
                    /*
                    if(strSaveFileName2 != "")
                    {
                        //升级文件2
                        byte[] resArr2 = new byte[iImageMcu2Len + iIamgelen2];
                        if (this.txt_Mcu2upgade1.Text != "" && this.ImageMcu2 != null) //MCU image
                        {
                            this.ImageMcu2.CopyTo(resArr2, 0);
                        }
                        if (this.txt_upgade2.Text != "" && this.Image2 != null)       //SOC image
                        {
                            this.Image2.CopyTo(resArr2, iImageMcu2Len);
                        }
  
                        pFileStream.Write(resArr2, 0, resArr2.Length);  //在此写入文件

                        CRC32.Reset();
                        CRC32.Crc(resArr2, resArr2.Length);
                        string strCrc2 = CRC32.crc.ToString("X8");
                        string strAddInfo2 = "L" + iIamgelen1.ToString("X8") + iIamgelen2.ToString("X8") + strCrc2;    //          
                        ByteInfoArr = ASCIIEncoding.ASCII.GetBytes(strAddInfo2);
                        pFileStream.Write(ByteInfoArr, 0, ByteInfoArr.Length);  //再次写入文件
                    }
                    */
                    this.labelSave.Text = fileName;
                    label_Result.Text = "升级包制作成功!\r\n\r\n名称:" + Path.GetFileName(fileName) + "  路径:单击▶▶打开文件所在处";
                    AppConfigProcess.SetConfigValue("SAVEPATH", Path.GetDirectoryName(saveFileDialog.FileName)); //升级包输出路径


                    AppConfigProcess.SetConfigValue("MCUFILE", txt_upgade1_path);     //保持源文件路径
                    AppConfigProcess.SetConfigValue("SOCFILE",  this.txt_upgade2_path);     //保持源文件路径
                   

                }

                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (pFileStream != null)
                {
                    pFileStream.Close();
                }
            }
        }

        private bool writeFile(byte[] pReadByte, string fileName)
        {
            FileStream pFileStream = null;
            try
            {
                pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);
                pFileStream.Write(pReadByte, 0, pReadByte.Length);
            }
            catch
            {
                return false;
            }
            finally
            {
                if (pFileStream != null)
                {
                    pFileStream.Close();
                }
            }
            return true;
        }


        void loadmcufile(string filepath) 
        {
            try
            {
                //this.txt_upgade1.Text = "";
                this.Image1 = null;
                label_MCUSofewareVersion.Text = "";
                label_MCUHardwareVersion.Text = "";
                label_McuImageSize.Text = "";
                label_McuProjectNo.Text = "";
                labelSave.Text = "";
                label_Result.Text = "";
                label_MCU项目编号.Visible = false;
                label_MCU硬件版本号.Visible = false;
                label_MCU软件版本号.Visible = false;
                label_MCU程序大小.Visible = false;

                
                
                bool flag = false;
                if(txt_upgade1.Text != "")
                {
                    filepath = txt_upgade1_path;
                }
                if(File.Exists(filepath))
                {
                    flag = true;
                    //txt_upgade1.Text = filepath;
                }
                else
                {
                    txt_upgade1.Text = "";
                    return;
                }


                if (flag == true)
                {
                    if (this.s_ImageName1 == "")
                    {
                        if (string.Compare(Path.GetExtension(txt_upgade1_path), ".xml", true) == 0)
                        {
                            XmlDocument doc = new XmlDocument();
                            doc.Load(txt_upgade1_path);
                            byte[] arr = GetIdentification(doc.ChildNodes);
                            if (Kn.DLMS.GXByteBuffer.IsAsciiString(arr))
                            {
                                this.s_ImageName1 = ASCIIEncoding.ASCII.GetString(arr);
                            }
                            else
                            {
                                this.s_ImageName1 = Kn.DLMS.GXDLMSTranslator.ToHex(arr);
                            }
                        }
                        else
                        {
                            this.s_ImageName1 = Path.GetFileNameWithoutExtension(txt_upgade1_path);
                        }
                    }

                    if (string.Compare(Path.GetExtension(txt_upgade1_path), ".xml", true) == 0)
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.Load(txt_upgade1_path);
                        byte[] image = null;
                        GetImage(doc.ChildNodes, ref image);
                        this.Image1 = image;
                    }
                    else
                    {
                        FileInfo info = new FileInfo(txt_upgade1_path);
                        if (info.Extension == ".hex" || info.Extension == ".HEX" || info.Extension == ".Hex")
                        {
                            HexFile tmp = new HexFile(txt_upgade1_path);
                            this.Image1 = tmp.AppImage;
                        }
                        if (info.Extension == ".mot" || info.Extension == ".MOT" || info.Extension == ".Mot")
                        {
                            int BootSize = 0x2000;
                            string strBootSize = AppConfigProcess.GetConfigXml("McuAppBootSize");     //保持最近一次选择的文件格式
                            if (strBootSize == "")
                            {
                                AppConfigProcess.SetConfigValue("McuAppBootSize", BootSize.ToString());
                            }
                            else
                            {
                                BootSize = Convert.ToInt32(strBootSize);
                            }
                            SRecordView tmp = new SRecordView(txt_upgade1_path, false, BootSize);  //!!
                            this.Image1 = tmp.AppImage;
                        }
                        if (info.Extension == ".bin" || info.Extension == ".BIN" || info.Extension == ".Bin")
                        {
                            this.Image1 = File.ReadAllBytes(txt_upgade1_path);
                        }

                    }

                    string strL = "";

                    // 5007 /  5011
                    if (this.Image1.Length > 8179)
                    {
                        this.strfileCode = ASCIIEncoding.ASCII.GetString(this.Image1, 8160, 5);       //0x1FE0  const unsigned char c_KnSoft[11]__attribute__( (at(0x3FE0)))="5011H210727";      // 内部程序版本号 //
                        this.s_str5007Ver = ASCIIEncoding.ASCII.GetString(this.Image1, 8171, 9);      //0x1FEB  const unsigned char c_SoftVersion[10]__attribute__( (at(0x3FEB)))="040521.06.";  // 软件版本号10字节//
                        strL = ASCIIEncoding.ASCII.GetString(this.Image1, this.Image1.Length - 25, 3);
                        this.strMcuHardwareVer = ASCIIEncoding.ASCII.GetString(this.Image1, 0x1FF5, 8);
                    }

                    // 5012 Bin文件
                    if (this.Image1.Length > 5012 && this.strfileCode.Substring(0, 2) != "50")
                    {
                        this.strfileCode = ASCIIEncoding.ASCII.GetString(this.Image1, 4992, 5);      //0x1380  #pragma section @@CNST VERCST  AT  3380H const unsigned char c_KnSoft[11]="5012.210817";           // 软件版本号 //
                        this.s_str5007Ver = ASCIIEncoding.ASCII.GetString(this.Image1, 5003, 9);     //0x138B  #pragma section @@CNST VERCST  AT  3380Hconst unsigned char c_SoftVersion[12]="170821.01.04";     // 内部程序版本号 //
                        strL = ASCIIEncoding.ASCII.GetString(this.Image1, this.Image1.Length - 25, 3);
                        this.strMcuHardwareVer = ASCIIEncoding.ASCII.GetString(this.Image1, 0x1397, 8);   //0x1397  #pragma section @@CNST VERCST  AT  3380H c_HardVersion[9]="5012V0.6";         // 硬件版本号 //
                    }

                    label_MCU项目编号.Visible = true;
                    label_MCU硬件版本号.Visible = true;
                    label_MCU软件版本号.Visible = true;
                    label_MCU程序大小.Visible = true;

                    label_MCUSofewareVersion.Text = s_str5007Ver;
                    label_MCUHardwareVersion.Text = strMcuHardwareVer;
                    float flen = this.Image1.Length;
                    flen /= 1024;
                    label_McuImageSize.Text = this.Image1.Length.ToString() + "B/" + flen.ToString("000.00") + "KB";
                    label_McuProjectNo.Text = this.strfileCode.Replace(".", "");

                    if ((this.strfileCode.Substring(0, 2) != "50" /*|| this.strfileCode.Substring(4, 1) != ".")*/ || strL == "L00"))
                    {
                        this.Image1 = null;
                        this.txt_upgade1.Text = "";
                        throw new Exception("illegal file ,please re-select!");
                    }

                    if (this.strfileCode == "5007.")
                    {
                        if (this.Image1.Length > (119 * 1024))
                        {
                            MessageBox.Show("Mcu file length > 119 KB", "");
                        }
                    }

                    else if (this.strfileCode == "5011.")
                    {
                        if (this.Image1.Length > (200 * 1024))
                        {
                            MessageBox.Show("Mcu file length > 200 KB");
                        }
                    }

                    else if (this.strfileCode == "5012.")
                    {
                        if (this.Image1.Length > (87 * 1024))
                        {
                            MessageBox.Show("Mcu file length > 87 KB");
                        }
                    }


                    AppConfigProcess.SetConfigValue("MCUPATH", Path.GetDirectoryName(txt_upgade1_path));     //保持最近一次选择的文件格式
                }
            }
            catch (Exception ex)
            {
                this.Image1 = null;
                label_MCUSofewareVersion.Text = "";
                label_MCUHardwareVersion.Text = "";
                label_McuImageSize.Text = "";
                label_McuProjectNo.Text = "";

                label_MCU项目编号.Visible = false;
                label_MCU硬件版本号.Visible = false;
                label_MCU软件版本号.Visible = false;
                label_MCU程序大小.Visible = false;
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /*
        void loadsocfile(string filepath)
        {
            string strfileSOCADDR = null;

            try
            {
                this.Image2 = null;

                bool flag = false;
                if (txt_upgade2.Text != "")
                {
                    filepath = txt_upgade2.Text;
                }
                if (File.Exists(filepath))
                {
                    flag = true;
                    txt_upgade2.Text = filepath;
                }
                else
                {
                    txt_upgade2.Text = "";
                    return;
                }

                if (flag == true)
                {
                    //this.btn_Combine.Enabled = true;
                    //this.txt_upgade2.Text = dlg.FileName;

                    if (this.s_ImageName2 == "")
                    {
                        if (string.Compare(Path.GetExtension(txt_upgade2.Text), ".xml", true) == 0)
                        {
                            XmlDocument doc = new XmlDocument();
                            doc.Load(txt_upgade2.Text);
                            byte[] arr = GetIdentification(doc.ChildNodes);
                            if (Kn.DLMS.GXByteBuffer.IsAsciiString(arr))
                            {
                                this.s_ImageName2 = ASCIIEncoding.ASCII.GetString(arr);
                            }
                            else
                            {
                                this.s_ImageName2 = Kn.DLMS.GXDLMSTranslator.ToHex(arr);
                            }
                        }
                        else
                        {
                            this.s_ImageName2 = Path.GetFileNameWithoutExtension(txt_upgade2.Text);
                        }
                    }

                    if (string.Compare(Path.GetExtension(txt_upgade2.Text), ".xml", true) == 0)
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.Load(txt_upgade2.Text);
                        byte[] image = null;
                        GetImage(doc.ChildNodes, ref image);
                        this.Image2 = image;
                    }
                    else
                    {
                        this.Image2 = File.ReadAllBytes(txt_upgade2.Text);
                    }

                    string strL = "";
                    if (this.Image2.Length > (3056 + 7))
                    {
                        strfileSOCADDR = ASCIIEncoding.ASCII.GetString(this.Image2, 3056, 7);
                        this.s_strSocaddrVer = ASCIIEncoding.ASCII.GetString(this.Image2, 3063, 8);
                        strL = ASCIIEncoding.ASCII.GetString(this.Image2, this.Image2.Length - 25, 1);
                    }

                    if (strfileSOCADDR != "SOCADDR" || strL == "L")
                    {
                        this.Image2 = null;
                        this.txt_upgade2.Text = "";
                        throw new Exception("illegal file ,please re-select!");
                    }

                    if (this.Image2.Length > (31 * 1024))
                    {
                        this.btn_Combine.Enabled = this.txt_upgade1.Text == "" ? false : true;
                        this.txt_upgade2.Text = "";
                        throw new Exception("Soc file length > 31 KB");
                    }

                    AppConfigProcess.SetConfigValue("SOCPATH", Path.GetDirectoryName(txt_upgade2.Text));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        */
        private void button_AutoOutputUpdateFile_Click(object sender, EventArgs e)
        {
            FileStream pFileStream = null;
            string fileName = null;
            byte[] ByteInfoArr = null;
            this.labelSave.Text = "";
            label_Result.Text = "";
            string strSaveFileName = "";
            string strSaveFileName1 = "";
            string strSaveFileName2 = "";

            string strSaveFileWithBin = "";

            //txt_Mcu2upgade1.Text = ""; //= AppConfigProcess.GetConfigXml("MCU2FILE");
            //txt_upgade2.Text = "";  //= AppConfigProcess.GetConfigXml("SOCFILE");

            
            loadmcufile(AppConfigProcess.GetConfigXml("MCUFILE"));
            try
            {
                if (this.txt_upgade1.Text == "" && this.txt_upgade2.Text == "" )
                {
                    throw new Exception("Please import the upgrade file frist.");
                }

                //确定文件名
                if (this.txt_upgade1.Text != "" && this.txt_upgade2.Text != "")
                {
                    strSaveFileName1 = "MS" + label_McuProjectNo.Text + label_MCUSofewareVersion.Text.Replace(".", "");
                }

                else if (this.txt_upgade1.Text != "" && this.txt_upgade2.Text == "")
                {
                    strSaveFileName1 = "M" + label_McuProjectNo.Text + label_MCUSofewareVersion.Text.Replace(".", "");
                }

                else if (this.txt_upgade1.Text == "" && this.txt_upgade2.Text != "")
                {
                    strSaveFileName1 = "S" + this.s_strSocaddrVer.Substring(1, 7);
                }


                //确定文件名
                if (this.txt_upgade2.Text != "")
                {
                    strSaveFileName2 = "MS" + label_Mcu2ProjectNo.Text + label_MCU2SofewareVersion.Text.Replace(".", "");
                }

                else if (this.txt_upgade2.Text == "")
                {
                    strSaveFileName2 = "M" + label_Mcu2ProjectNo.Text + label_MCU2SofewareVersion.Text.Replace(".", "");
                }

                else if (this.txt_upgade2.Text != "")
                {
                    strSaveFileName2 = "S" + this.s_strSocaddrVer.Substring(1, 7);
                }

                strSaveFileWithBin = "\\" + strSaveFileName1 + strSaveFileName2 + ".BIN";
                Int32 iIamgelen1 = (this.txt_upgade1.Text != "" && this.Image1 != null) ? this.Image1.Length : 0;
                Int32 iIamgelen2 = (this.txt_upgade2.Text != "" && this.Image2 != null) ? this.Image2.Length : 0;


                bool flag = false;
                string sPath = AppConfigProcess.GetConfigXml("SAVEPATH");
                if (Directory.Exists(sPath))
                {
                    fileName = sPath + strSaveFileWithBin;   //"C:\\Users\\Administrator\\Desktop\\M501215102001.BIN"
                    flag = true;
                }
                else
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Title = "Combine Upgade file";
                    saveFileDialog.Filter = "BIN format file(*.BIN)|*.BIN";
                    saveFileDialog.RestoreDirectory = false;
                    saveFileDialog.CheckPathExists = true;
                    //string sPath = AppConfigProcess.GetConfigXml("SAVEPATH");
                    if (Directory.Exists(sPath)) saveFileDialog.InitialDirectory = sPath;
                    saveFileDialog.FileName = strSaveFileName1 + strSaveFileName2;
                    DialogResult dialogResult = saveFileDialog.ShowDialog(this);
                    if (dialogResult == DialogResult.OK)
                    {
                        fileName = saveFileDialog.FileName;   //"C:\\Users\\Administrator\\Desktop\\M501215102001.BIN"
                        flag = true;
                    }
                }



                if (flag == true)
                {
                    System.IO.File.Delete(fileName);
                    pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);

                    if (strSaveFileName1 != "")
                    {
                        //升级文件1
                        byte[] resArr = new byte[iIamgelen1 + iIamgelen2];
                        if (this.txt_upgade1.Text != "" && this.Image1 != null)
                        {
                            this.Image1.CopyTo(resArr, 0);
                        }
                        if (this.txt_upgade2.Text != "" && this.Image2 != null)
                        {
                            this.Image2.CopyTo(resArr, iIamgelen1);
                        }
                        //fileName = saveFileDialog.FileName;
                        //System.IO.File.Delete(fileName);
                        //pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);
                        pFileStream.Write(resArr, 0, resArr.Length);

                        CRC32.Reset();
                        CRC32.Crc(resArr, resArr.Length);
                        string strCrc = CRC32.crc.ToString("X8");
                        string strAddInfo = "L" + iIamgelen1.ToString("X8") + iIamgelen2.ToString("X8") + strCrc;    //          
                        ByteInfoArr = ASCIIEncoding.ASCII.GetBytes(strAddInfo);
                        pFileStream.Write(ByteInfoArr, 0, ByteInfoArr.Length);  //再次写入文件     
                    }


                   
                    //MessageBox.Show("File Combine successful！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.labelSave.Text = fileName;
                    label_Result.Text = "升级包制作成功!\r\n\r\n名称:" + Path.GetFileName(fileName) + "  路径:单击▶▶打开文件所在处";
                    AppConfigProcess.SetConfigValue("SAVEPATH", Path.GetDirectoryName(fileName)); //升级包输出路径

                    AppConfigProcess.SetConfigValue("MCUFILE", txt_upgade1_path);     //保持源文件路径
                    AppConfigProcess.SetConfigValue("SOCFILE", txt_upgade2_path);     //保持源文件路径

                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (pFileStream != null)
                {
                    pFileStream.Close();
                }
            }
        }

        private void button_Open_Click(object sender, EventArgs e)
        {
            string strPath = labelSave.Text.Replace("升级包制作成功:\r\n", "");
            string FilePath = Path.GetDirectoryName(strPath);;
            string FileName = Path.GetFileName(strPath);
            System.Diagnostics.Process.Start("Explorer", "/select," + FilePath + "\\" + FileName);
        }

        private void Form1_Click(object sender, EventArgs e)
        {

        }

        private void labelSave_Click(object sender, EventArgs e)
        {
            string strPath = labelSave.Text;
            string FilePath = Path.GetDirectoryName(strPath);
            string FileName = Path.GetFileName(strPath);
            System.Diagnostics.Process.Start("Explorer", "/select," + FilePath + "\\" + FileName);
        }

        private void label_Result_Click(object sender, EventArgs e)
        {
            string strPath = labelSave.Text;
            string FilePath = Path.GetDirectoryName(strPath);
            string FileName = Path.GetFileName(strPath);
            System.Diagnostics.Process.Start("Explorer", "/select," + FilePath + "\\" + FileName);
        }
    }
}
